package org.example.log.task;

import com.alibaba.fastjson.JSONObject;
import lombok.Setter;
import org.example.log.dao.SaveLoggingTaskDao;
import org.example.log.dto.SaveLogDto;
import org.example.log.tool.ModelFieldCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用模型落日志处理任务
 *
 * @author hero生仔
 * @date 2025/8/2
 */
@Setter
@Component
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SaveLoggingTask implements Runnable {

    @Autowired
    private ModelFieldCache modelFieldCache;

    @Autowired
    private SaveLoggingTaskDao saveLoggingTaskDao;

    /**
     * 模型中间层字段映射
     */
    private JSONObject fieldJsonObject;

    /**
     * 树名
     */
    private SaveLogDto saveLogDto;

    /**
     * 模型名
     */
    private String modelName;


    @Override
    public void run() {
        Map<String, Object> params = new HashMap<>();
        String tableName = modelFieldCache.getTableName(modelName);
        params.put("tableName", tableName);
        List<String> dbNames = new ArrayList<>();
        List<String> dbValues = new ArrayList<>();
        for (Map.Entry<String, Object> entry : fieldJsonObject.entrySet()) {
            // 字段名
            String dbName = entry.getKey();
            dbNames.add(dbName);
            // 中间层字段
            String middleValue = String.valueOf(saveLogDto.getResult().getString((String) entry.getValue()));
            dbValues.add(middleValue);
        }
        params.put("dbNameList", dbNames);
        params.put("dbValueList", dbValues);
        appendParams(dbNames, dbValues);
        // 落日志表
        saveLoggingTaskDao.saveModelDataLog(params);
    }

    /**
     * 添加额外的参数
     *
     * @param dbNames  字段集合
     * @param dbValues 字段的值集合
     */
    private void appendParams(List<String> dbNames, List<String> dbValues) {
        dbNames.add("bussNo");
        dbNames.add("dcsTree");
        dbValues.add(saveLogDto.getBussNo());
        dbValues.add(saveLogDto.getDcsTree());
    }

    /**
     * 初始化属性
     *
     * @param modelName       模型名
     * @param saveLogDto      存储对象
     * @param fieldJsonObject 中间层字段
     */
    public void setBaseInfo(String modelName, SaveLogDto saveLogDto, JSONObject fieldJsonObject) {
        this.modelName = modelName;
        this.saveLogDto = saveLogDto;
        this.fieldJsonObject = fieldJsonObject;
    }
}
